<!-- 用户编辑弹窗 -->
<template>
  <el-dialog
    width="680px"
    :visible="visible"
    :lock-scroll="false"
    :destroy-on-close="true"
    custom-class="ele-dialog-form"
    :title="isUpdate?'编辑账号':'新增账户'"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="roleIsTeacher?rulesAdd:rules"
      label-width="82px">
      <el-row :gutter="15">
        <el-col :sm="12">
          <el-form-item label="账户名称:" prop="username">
            <el-input
              clearable
              :maxlength="20"
              :disabled="isUpdate"
              v-model="form.username"
              placeholder="请输入账户名称"/>
          </el-form-item>
          <el-form-item
            label="登录密码:"
            prop="password">
            <el-input
              show-password
              :maxlength="20"
              v-model="form.password"
              placeholder="请输入登录密码"/>
          </el-form-item>
          <el-form-item label="姓名:" prop="realname">
            <el-input
              clearable
              :maxlength="20"
              v-model="form.realname"
              placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item label="性别:" prop="gender">
            <el-select
              clearable
              class="ele-block"
              v-model="form.gender"
              placeholder="请选择性别">
              <el-option label="男" :value="1"/>
              <el-option label="女" :value="2"/>
              <el-option label="未知" :value="0"/>
            </el-select>
          </el-form-item>
          
        </el-col>
        <el-col :sm="12">
          
          <el-form-item label="角色:" prop="role_ids">
            <el-select
              multiple
              clearable
              class="ele-block"
              v-model="form.role_ids"
              placeholder="请选择角色">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"/>
            </el-select>
          </el-form-item>
          <el-form-item label="所在城市:" prop="city">
            <el-cascader
              clearable
              v-model="city"
              class="ele-fluid"
              placeholder="请选择省市区"
              :options="regions.cityData"
              popper-class="ele-pop-wrap-higher"/>
          </el-form-item>
          <el-form-item label="街道:" prop="streets_code">
                <el-select style="width:100%" clearable
                :disabled="!form.district_code"
                v-model="form.streets_code"
                placeholder="请输入街道">
                  <el-option :value="item.streets_code" :label="item.ext_name" v-for="(item,index) in streetsList" :key="index"/>
                </el-select>
            </el-form-item>
            <el-form-item label="所属学校:" prop="schoole_id">
            <el-select style="width:100%" clearable
                :disabled="!form.streets_code"
                v-model="form.schoole_id"
                placeholder="请输入所属学校">
                  <el-option :value="item.id" :label="item.title" v-for="(item,index) in schoolList" :key="index"/>
                </el-select>
              </el-form-item>
          <el-form-item label="联系方式:" prop="mobile">
            <el-input
              clearable
              :maxlength="11"
              v-model="form.mobile"
              placeholder="请输入联系方式"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button
        @click="updateVisible(false)">取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save">确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import validate from 'ele-admin/packages/validate';
import regions from 'ele-admin/packages/regions';
export default {
  name: 'UserEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  components: {},
  data() {
    return {
      roleList:[],
      // 省市区数据
      regions: regions,
      // 选中的省市区
      city: [],
      // 选中的省市
      provinceCity: [],
      // 选中的省
      province: [],
      // 表单数据
      form: {
        username: '',
        realname: "",
        role_ids: [],
        province_code:'',
        city_code:'',
        district_code:'',
        streets_code:'',
        schoole_id: '',
        gender:''
      },
      // 表单验证规则
      rules: {
        username: [
          {
            required: true,
            type: 'string',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入用户账号'));
              }
              this.$http.get('/user/checkUser?username=' + value).then(res => {
                if (res.data.code !== 0 || !res.data.data.length) {
                  return callback();
                }
                if (this.isUpdate && res.data.data[0].username === this.data.username) {
                  return callback();
                }
                callback(new Error('账号已经存在'));
              }).catch(() => {
                callback();
              });
            }
          }
        ],
        realname: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
       
        role_ids: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ],
        mobile: [
          {required: true,pattern: validate.phone, message: '手机号格式不正确', trigger: 'blur'}
        ],
        password:[
          { pattern: /^(?=.*[A-Za-z])[\w]{6,12}$/, message: '登录密码格式不正确,6-12位数字加字母', trigger: 'blur'}
        ],
      },
      roleIsTeacher:false,
      rulesAdd: {
        username: [
          {
            required: true,
            type: 'string',
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('请输入用户账号'));
              }
              this.$http.get('/user/checkUser?username=' + value).then(res => {
                if (res.data.code !== 0 || !res.data.data.length) {
                  return callback();
                }
                if (this.isUpdate && res.data.data[0].username === this.data.username) {
                  return callback();
                }
                callback(new Error('账号已经存在'));
              }).catch(() => {
                callback();
              });
            }
          }
        ],
        realname: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        password:[
          {required: true, pattern: /^(?=.*[A-Za-z])[\w]{6,12}$/, message: '登录密码格式不正确,6-12位数字加字母', trigger: 'blur'}
        ],
        role_ids: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ],
        mobile: [
          {required: true,pattern: validate.phone, message: '手机号格式不正确', trigger: 'blur'}
        ],
        
        city_code: [
          {required: true, message: '请选择所选城市', trigger: 'change'}
        ],
        streets_code: [
          {required: true, message: '请选择街道', trigger: 'change'}
        ],
        schoole_id: [
          {required: true, message: '请选择所选学校', trigger: 'change'}
        ],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      streetsList: [],
      schoolList:[],
    };
  },
  watch: {
    visible(val) { 
      if (val) {  this.queryRoles()} 
    },
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data, {
          role_ids: this.data.roles.map(d => d.id)
        });
        // 取值赋予城市组件
        this.city = this.data.city;
        // 清空密码输入框
        this.form.password = ''
        this.isUpdate = true;
      } else {
        this.form = {};
        this.isUpdate = false;
        // 清空省市区控件
        this.city = [];
      }
    },
    city(val) {
      if (val && val.length > 0) { 
        this.form.province_code=val[0]
        this.form.city_code=val[1]
        this.form.district_code = val[2]
        if (this.form.district_code) {
          this.getStreetsList()
        }
      }
    },
    'form.streets_code': {
      handler: function () { 
          this.getSchoolList()
      },
      deep:true
    },
    'form.role_ids': {
      handler: function (newVal) { 
        if(newVal.indexOf(10) !== -1){ 
          this.roleIsTeacher=true
        }else{
          this.roleIsTeacher=false
        }
      },
      deep:true
    }
  },
  mounted() {
   
  },
  methods: {
   /* 查询角色列表 */
   queryRoles() {
      this.$http.get('/role/getRoleList').then(res => {
        if (res.data.code === 0) {
          this.roleList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    getStreetsList() {
      this.$http
        .get("/user/getStreetsList", { params: { district_code: this.form.district_code } })
        .then(res => {
          this.streetsList = res.data.data;
        })
        .catch(e => {
          this.$message.error(e.message);
        });
    },
    getSchoolList() {
      this.$http
        .get("/user/getSchoolList", { params: { streets_code:this.form.streets_code } })
        .then(res => {
          this.schoolList = res.data.data;
        })
        .catch(e => {
          this.$message.error(e.message);
        });
    },
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // let psdRule = /\d{17}(\d|X)$/.test(this.form.password)
          // if (this.form.password&&!psdRule) { 
          //   return false
          // }
          this.loading = true;
          // 城市数据处理
          this.form = Object.assign({}, this.form, {
            city: this.city
          });
          this.$http.post('/user/edit', this.form).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message({type: 'success', message: res.data.msg});
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
  }
}
</script>

<style scoped>
</style>
